<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Maneger extends Model {
    
    private $action = FALSE;
    private $id = 0;
    private $db_table;
    private $configs = array();
    private $delete = array();
    private $url = NULL;
    private $link_add = TRUE;
    
    private $field = array();
    private $primary_key = '';
    
    function Maneger() {
    	
        parent::Model();
    }
    
    public function run($table, $uri = 3) {
        
        $this->db_table = $table;
        
        $this->action = $this->uri->segment($uri, FALSE);
        $this->id = $this->uri->segment($uri + 1, 0);
        
        if ( $this->action === FALSE ) {
            
            return $this->table($table);
        }
        
        if ( method_exists($this, $this->action) ) {
            
            $action = $this->action;
            return $this->$action();
        }
        
    }
    
    public function set_settings($array, $val = NULL) {
        
        if ( is_array($array) ) {
            
            $this->configs = $array;
        }
        else {
            
            $this->configs[$array] = $val;
        }
    }
    
    public function set_delete($array) {
        
        if ( is_array($array) ) {
            
            $this->delete = $array;
        }
    }
    
    public function set_url($url) {
        
        $this->url = $url;
    }
    
    public function set_link_add($val) {
        
        $this->link_add = $val;
    }
    
    private function table($table) {
        
        $query = $this->db->get($table);
        
        if ($this->url == NULL) {
        
            $url = $this->uri->uri_string();
        }
        else {
            
            $url = $this->url;
        }
        
        foreach ($query->field_data() as $field) {
            
            $this->field[] = $field->name;
            
            if ( !in_array($field->name, $this->delete) )
            {
                $tab_head[] = $this->lang->line($this->db_table.'_'.$field->name);
            }
            
            if ($field->primary_key) {
                
                $this->primary_key = $field->name;
            }
        }
               
        $tab_head[] = 'Действия';
        
        foreach($query->result_array() as $row) {
            
            foreach ($this->field as $col) {
                
                if ( !in_array($col, $this->delete) )
                {
                    $tab_content[$col] = $this->parse_config($col, $row[$col]);
                }
            }
            
            $tab_content['edite']  = anchor($url.'/edit/'.$row[$this->primary_key], img('images/admin/pencil_small.png'), array('title' => 'Изменить'));
            $tab_content['edite'] .= ' '.anchor($url.'/delete/'.$row[$this->primary_key], img('images/admin/cross_small.png'), array('title' => 'Удалить'));
            
            $this->table->add_row($tab_content);
        }
        
        $this->table->set_heading($tab_head);
        
        $end = $this->table->generate();
        $end .= ( $this->link_add ) ? '<br>'.anchor($url.'/add/', 'Добавить') : '';
        
        return $end;
    }

    private function add() {
        
        if (count($_POST) > 0) {
            
            if ($this->db->insert($this->db_table, $_POST) === TRUE)
    		{
    			return 'Добавлено';
    		}
    		else {
    		    return 'Неудалось добавить';
    		}
        }
        
        $query = $this->db->get($this->db_table);
        
        return $this->form($query);
    }

    private function edit() {
        
        if ($this->id <= 0) {
            
            return 'Такой записи не существует.';
        }
        
        $primary = $this->db->primary($this->db_table);
        
        if (count($_POST) > 0) {
            
            if ($this->db->update($this->db_table, $_POST, array($primary => $this->id)) === TRUE)
    		{
    			return 'Изменено';
    		}
    		else {
    		    return 'Неудалось изменить';
    		}
        }
        
        $query = $this->db->get_where($this->db_table, array($primary => $this->id));
        
        return $this->form($query, TRUE);
    }
    
    private function delete() {
        
        if ($this->id <= 0) {
            
            return 'Такой записи не существует.';
        }
        
        $primary = $this->db->primary($this->db_table);
        
        if ($this->db->delete($this->db_table, array($primary => $this->id)) === TRUE)
		{
			return 'Удалено';
		}
		else {
		    return 'Неудалось удалить';
		}
    }
    
    private function form($query, $edite = FALSE) {
        
        $data['fields'] = $query->field_data();
        $data['action'] = $this->uri->uri_string();
        $data['value']  = ( $edite ) ? $query->row_array() : array();
        $data['table']  = $this->db_table;
        
        return $this->load->view('maneger/form', $data, TRUE);
    }
    
    private function parse_config($name, $value) {
        
        if ( !isset($this->configs[$name]) ) {
            
            return $value;
        }
        
        foreach ($this->configs[$name] as $key => $row) {
            
            return $this->parse_func($key, $row, $value);
        }
    }
    
    private function parse_func($name, $array, $value) {
        
        switch($name) {
            
            case 'word_limiter':
                
                $array['limit'] = ( isset($array['limit']) ) ? $array['limit'] : 20;
                $array['end_char'] = ( isset($array['end_char']) ) ? $array['end_char'] : '&#8230;';
                
                return word_limiter($value, $array['limit'], $array['end_char']);
                break;
                
            case 'character_limiter':
                
                $array['limit'] = ( isset($array['limit']) ) ? $array['limit'] : 100;
                $array['end_char'] = ( isset($array['end_char']) ) ? $array['end_char'] : '&#8230;';
                
                return character_limiter($value, $array['limit'], $array['end_char']);
                break;
                
            case 'value':
                
                if ($value == $array['if']) {
                    
                    return $array['to_if'];
                }
                else {
                    
                    return ( isset($array['else']) ) ? $array['else'] : $value;
                }
                
                break;
            case 'yes_no':
                
                if ($value == 1) {
                    
                    return 'Да';
                }
                else {
                    return 'Нет';
                }
                
                break;
            case 'date':
                
                return date($array['mask'], $value);
                break;
        }
    }

}